let audio = wx.createInnerAudioContext({
    useWebAudioImplement: true
})
const db = wx.cloud.database()
let common = {
    /**
     * 根据歌曲地址播放音频
     */
    playAudioBySentence(address) { // 播放音频
        console.log('调用playAudioBySentence')
        audio.src = address
        audio.play()
        audio.onStop(res => {
            // 清空音频链接
            audio.src = ''
        })
    },

    /**
     * 组件暂停播放 TODO
     */
    cptstopAudio() {
        console.log("执行stop")
        audio.stop()
    },

    /**
     * 查询单词
     */
    async qureyWordAuido(that, inputText) {
        let cptword = {}
        wx.showLoading({
            title: '查询中...',
            mask: true
        })
        let {
            result
        } = await wx.cloud.callFunction({
            name: 'queryWord',
            data: {
                content: inputText,
            }
        })
        wx.hideLoading()
        console.log('查询单词结果：', result)

        if (result.length == 0) { // 如果数据长度为0，表示没有相关记录
            wx.showToast({
                title: '未找到相关单词',
                icon: 'none'
            })
            return // 终止程序
        }
        await wx.setStorageSync('queryWord', result[0])


        // 能走到这里，表示已经查询到单词，将获取的整体数据传给组件，以便组件随意使用数据
        cptword = result[0] // 只取查询结果的第一条数据
        new Promise(() => {
            // 执行组件内方法，让组件内的元素显示
            that.component.show()
            if (cptword.lyric) {
                this.processLyric(cptword)
            }
            that.setData({
                cptword: cptword
            })
            this.playAudioBySentence(cptword.address)
        })

        // 判断搜索单词是否已收入生词本
        await wx.cloud.callFunction({
            name: 'getDictWord',
            data: {
                type: "noteBook"
            }
        }).then(res => {
            if (res.result[0] && res.result[0].noteBook) {
                let notelist = res.result[0].noteBook
                notelist.forEach(item => {
                    if (item.content == cptword.content) {
                        that.setData({
                            popShowNot: false
                        })
                    } else {
                        that.setData({
                            popShowNot: true
                        })
                    }
                })
            } else {
                that.setData({
                    popShowNot: true
                })
            }
        })
    },

    /**
     * 查询音频状态
     */
    async qureyAudioStatus(word) {
        let {
            result
        } = await wx.cloud.callFunction({
            name: 'getDictWord',
            data: {
                type: 'audioStatus',
                content: word
            }
        })
        console.log(result)
        if (result[0] && result[0].address) { // 判断单词状态
            wx.showToast({
                title: '该单词音频正在审核中',
                icon: "none",
                duration: 1500
            })
        } else {
            wx.showToast({
                title: '详情页可上传音频哦',
                icon: "none",
                duration: 1500
            })
        }
    },

    /**
     * 组件中加入音频
     */
    async poppupAddVedio(word, id) {
        let {
            result
        } = await wx.cloud.callFunction({
            name: 'getDictWord',
            data: {
                type: 'audioStatus',
                content: word
            }
        })
        console.log(result)
        if (result[0] && result[0].address) { // 判断单词状态
            wx.showToast({
                title: '该单词音频正在审核中',
                icon: "none",
                duration: 1500
            })
        } else {
            // word_type = e.currentTarget.dataset.type
            wx.navigateTo({
                url: '/pages/audio/upWordAudio/upWordAudio?id=' + id + '&content=' + word + "&uptype=" + 'firstUp'
            })
        }
    },

    /**
     * 加入生词本并缓存到随机单词列表
     */
    async addNoteWord(word, content, _id) {
        wx.showLoading({
            title: '数据加载中...',
            mask: true
        })
        await wx.cloud.callFunction({
            name: 'addDictWord',
            data: {
                type: 'addnote',
                word: {
                    content,
                    _id
                }
            }
        })
        new Promise(() => {
            if (!wx.getStorageSync('randomWord')) {
                console.log('dfsf')
                wx.setStorageSync('randomWord', [{
                    content: word.content,
                    pron: word.pron,
                    definition: word.definition
                }])
            } else {
                let newRandomWord = wx.getStorageSync('randomWord').concat({
                    content: word.content,
                    pron: word.pron,
                    definition: word.definition
                })
                wx.setStorageSync('randomWord', newRandomWord)
            }
            wx.hideLoading()
        })
    },

    /**
     * 取消添加的单词
     */
    async delNoteWord(_id) {
        wx.showLoading({
            title: '数据加载中...',
            mask: true
        })

        await wx.cloud.callFunction({
            name: 'removeDictWord',
            data: {
                type: 'rvmnote',
                id: _id
            }
        }).then(res => {

            wx.hideLoading()
            console.log(JSON.stringify(res))
        })
    },

    /**
     * 收藏单词
     */
    async addStar(content, _id) {
        wx.showLoading({
            title: '数据加载中...',
            mask: true
        })
        await wx.cloud.callFunction({
            name: 'addDictWord',
            data: {
                type: 'addstar',
                word: {
                    content,
                    _id
                }
            }
        })
        wx.hideLoading({})
    },

    /**
     * 歌词加粗
     */
    processLyric(Lyric) {
        let lyricTex = `<p>${Lyric.lyric}</p>`.replaceAll(Lyric.content, `<span style="font-weight:bold;">${Lyric.content}</span>`) // 单词加粗
        if (lyricTex.match(/[\u4e00-\u9fa5]/g)) {
            let reg = lyricTex.match(/[\u4e00-\u9fa5]/g).join('') // 提取汉字
            // console.log('reg', reg)
            Lyric.lyric = lyricTex.replaceAll(reg, `<span style='font-size:17px; font-family:Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;'><br>${reg}<br></span>`)
            return Lyric
        }

    },

    /**
     * 取消收藏的单词
     */
    async cancelStar(_id) {
        wx.showLoading({
            title: '数据加载中...',
            mask: true
        })
        await wx.cloud.callFunction({
            name: 'removeDictWord',
            data: {
                type: 'rvmStar',
                id: _id
            }
        }).then(() => {
            wx.hideLoading({})
        })
    },

    /**
     * 更新用户数据
     */
    async upUserData() {
        wx.showLoading({
            title: '保存数据中...',
            mask:true
        })

        await wx.cloud.callFunction({
            name: 'updateData',
            data: {
                cet6Progress: wx.getStorageSync('cet6Progress'),
                cet4Progress: wx.getStorageSync('cet4Progress'),
                kaoyanProgress: wx.getStorageSync('kaoyanProgress'),
                lineData: wx.getStorageSync('lineData')
            }
        }).then(res =>{
            console.log('res',res)
            wx.hideLoading({})
        })
    },

    async autoCard(time, year, mon, day) {
        console.log('time', time, year, mon, day)
        await db.collection('calendar').add({
            data: {
                year: year,
                month: mon,
                date: day
            }
        })
        wx.setStorageSync('punchCard', {
            punchCard: "alreadCard",
            today_time: time
        })

    }
}

module.exports = common;